/**
 * Copyright (C) 2008 GeoScheduler Team, as stated on <http://www.geoscheduler.org/authors>.
 * 
 * This file is part of GeoScheduler.
 * 
 * GeoScheduler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GeoScheduler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with GeoScheduler. If not, see <http://www.gnu.org/licenses/>.
 */

package org.geoscheduler.commons.marshaller.decls;

import org.geoscheduler.commons.marshaller.JSONFieldDecl;
import org.geoscheduler.commons.marshaller.JSONMarshaller;
import org.geoscheduler.commons.tools.PropertyDescriptor;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 
 * <h2>JSONEntityField</h2>
 * <p>
 * HAS-A entity object graph marshaller/unmarshaller
 * </p>
 * 
 * @author lko
 */
public class JSONEntityField<T> extends JSONAbstractFieldDecl<T> {

	public JSONEntityField(PropertyDescriptor<T> desc, T defValue) {
		super(desc, defValue);
	}

	public JSONEntityField(PropertyDescriptor<T> desc) {
		super(desc);
	}

	/**
	 * @see org.geoscheduler.commons.marshaller.JSONFieldDecl#marshall(org.geoscheduler.commons.marshaller.JSONMarshaller,
	 *      java.lang.Object, org.json.JSONObject)
	 */
	public JSONObject marshall(JSONMarshaller marshaller, Object instance, JSONObject obj) throws JSONException {
		Object fieldVal = getDescriptor().getValue(instance);
		obj.put(getName(), fieldVal == null ? JSONObject.NULL : marshaller.marshall(fieldVal, new JSONObject()));
		return obj;
	}

	/**
	 * @see org.geoscheduler.commons.marshaller.JSONFieldDecl#unmarshall(org.geoscheduler.commons.marshaller.JSONMarshaller,
	 *      java.lang.Object, org.json.JSONObject)
	 */
	public Object unmarshall(JSONMarshaller marshaller, Object instance, JSONObject obj) throws JSONException {
		JSONObject child = obj.getJSONObject(getName());
		T childInst = null;
		Class<T> type = getType();
		try {
			instance = type.newInstance();
		} catch (Exception ex) {
			throw new IllegalArgumentException("failed to create instance of type " + type, ex);
		}
		marshaller.unmarshall(childInst, child);
		getDescriptor().setValue(instance, childInst);
		return instance;
	}

	public static class Factory extends BaseAbstractFactory<Object> {

		public JSONFieldDecl<Object> create(PropertyDescriptor<Object> desc, JSONMarshaller marshaller) {
			return new JSONEntityField<Object>(desc);
		}

		public boolean isApplicable(PropertyDescriptor<?> desc) {
			return super.isApplicable(desc);
		}

	}
}
